package com.byx.chatclient.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.view.View;

import androidx.appcompat.content.res.AppCompatResources;

import com.byx.chatclient.R;
import com.byx.chatclient.bean.PopupMenuItem;
import com.byx.chatclient.widget.PopupMenu;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * PopupWindowAdapter
 *
 * @author Superb
 * @date 2021/4/24 16:36
 */
public class PopupMenuAdapter extends BaseQuickAdapter<PopupMenuItem, BaseViewHolder> {
    private static final int LAYOUT_RES_ID = R.layout.layout_popup_menu_item;
    private PopupMenu.OnMenuItemClickListener mListener;

    public PopupMenuAdapter(@Nullable List<PopupMenuItem> data) {
        super(LAYOUT_RES_ID, data);
    }

    public PopupMenuAdapter() {
        super(LAYOUT_RES_ID);
    }

    @Override
    public void onBindViewHolder(@NotNull BaseViewHolder holder, int position) {
        if (position == 0){
            holder.itemView.setBackground(addStateDrawable(getContext(),-1,R.drawable.popup_top_pressed));
        }else if (position == getItemCount() - 1){
            holder.itemView.setBackground(addStateDrawable(getContext(),-1,R.drawable.popup_bottom_pressed));
        }else {
            holder.itemView.setBackground(addStateDrawable(getContext(),-1,R.drawable.popup_middle_pressed));
        }
        holder.itemView.setOnClickListener(v -> {
            if (mListener != null){
                mListener.onMenuItemClick(position);
            }

        });
        super.onBindViewHolder(holder, position);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, PopupMenuItem popupMenuItem) {

        baseViewHolder.setText(R.id.menu_text,popupMenuItem.getText());
        baseViewHolder.setImageDrawable(R.id.menu_icon,popupMenuItem.getDrawable());
    }

    private StateListDrawable addStateDrawable(Context context, int normalId, int pressedId){
        StateListDrawable sd = new StateListDrawable();
        Drawable normal = normalId == -1 ? null : AppCompatResources.getDrawable(context,normalId);
        Drawable pressed = pressedId == -1 ? null : context.getResources().getDrawable(pressedId);
        sd.addState(new int[]{android.R.attr.state_pressed}, pressed);
        sd.addState(new int[]{}, normal);
        return sd;
    }

    public void setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener listener) {
        mListener = listener;
    }
}
